package com.dd.security.jwt;

import com.alibaba.fastjson.JSONObject;
import com.dd.security.jwt.property.JwtTokenConfig;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Getter
@Setter
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    private UserDetailsService userDetailsService;

    private JwtTokenHelper jwtTokenHelper;

    private JwtTokenConfig jwtTokenConfig;

    public JwtAuthTokenFilter(JwtTokenConfig jwtTokenConfig,JwtTokenHelper jwtTokenHelper){
        this.jwtTokenConfig = jwtTokenConfig;
        this.jwtTokenHelper = jwtTokenHelper;
        this.jwtTokenHelper.setJwtTokenConfig(jwtTokenConfig);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader(this.jwtTokenConfig.getTokenHeadKey());
        if (authHeader != null && authHeader.startsWith(this.jwtTokenConfig.getTokenHead())) {
            String authToken = authHeader.substring(this.jwtTokenConfig.getTokenHead().length());// The part after "Bearer "
            String userName = jwtTokenHelper.getUserNameFromToken(authToken);
            log.info("checking userId:{}", userName);
            if (StringUtils.isNotBlank(userName)) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(userName);
                if (jwtTokenHelper.validateToken(authToken)) {
                    //验证成功后讲用户角色信息放入UsernamePasswordAuthenticationToken
                    // 将在AccessDecisionManager.decide()方法中与访问地址要求的角色进行比较
                    log.info("用户验证成功，用户信息"+JSONObject.toJSONString(userDetails));
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
